package com.lagou.cluster.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lagou.cluster.entity.JobInfo;
import com.lagou.cluster.mapper.JobInfoMapper;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class JobInfoService {
    @Autowired
    private JobInfoMapper jobInfoMapper;
    private RedissonClient redissonClient;
    private Logger log  = LoggerFactory.getLogger(JobInfoService.class);
    Cache<String, List<JobInfo>> caches = CacheBuilder.newBuilder()
            .maximumSize(1)
            .expireAfterWrite(1, TimeUnit.MINUTES).build();

    @Autowired
    public void setRedissonClient(RedissonClient redissonClient) {
       this.redissonClient = redissonClient;
    }

    /**
     * 1.本地缓存取，本地缓存取的时候，会调用二级缓存redis的数据
     * 2.只有当redis挂掉，或者redis过期的时候，才会从数据库取。
     * @return
     */
    public List<JobInfo> list() {
        try {
            return caches.get("job_info", this::dbList);
        } catch (ExecutionException e) {
            //一般不会发生这个异常
            log.warn(e.getMessage());
        }
        return null;
    }

    List dbList() {
        log.info("本地缓存过期...");
        try {
            RList list = redissonClient.getList("job_info");
            if (list != null && !list.isEmpty()) {
                return list;
            }
            list.addAll(this.jobInfoMapper.selectList(new QueryWrapper<>()));
            list.expire(2, TimeUnit.MINUTES);
            return list;
        } catch (Exception e) {
            log.warn(e.getMessage());
            return this.jobInfoMapper.selectList(new QueryWrapper<>());
        }
    }

    public int save(JobInfo info) {
        int result = 0;
        if (info.getId() != null && info.getId()>0) {
            this.jobInfoMapper.updateById(info);
        } else {
            this.jobInfoMapper.insert(info);
        }
        try {
            this.redissonClient.getList("job_info").clear();
        } catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
            // 不删本地缓存 ???
        }
        return result;
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    public int delete(int id) {
        JobInfo info = new JobInfo();
        info.setId(id);
        info.setState((short)0);
        try {
            this.redissonClient.getList("job_info").clear();
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        return this.jobInfoMapper.updateById(info);
    }

}
